package com.xl.bigdata.es.search;

import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.FieldSortBuilder;
import org.elasticsearch.search.sort.SortOrder;

import java.io.IOException;

/**
 * @ClassName SearchAPI
 * @Description TODO
 * @Author xl.gao
 * @Date 2022/1/4 16:02
 * @Version
 */
public class SearchAPI {

    public static String searchAPI(RestHighLevelClient client, String index){

        TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("citycomple", "广州市");

        SearchRequest searchRequest = new SearchRequest();
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        searchSourceBuilder.query(termQueryBuilder);

        searchSourceBuilder.from(0);
        searchSourceBuilder.size(10);

        // 基于字段排序
        searchSourceBuilder.sort(new FieldSortBuilder("citycomple").order(SortOrder.ASC));
        // sourceBuilder.sort(new ScoreSortBuilder().order(SortOrder.DESC));
        // 基于得分排序

        if(false){
            searchSourceBuilder.fetchSource(false);
        }



        // 包含字段
        String[] includeFields = new String[] {"citycomple"};
//        String[] excludeFields = new String[] {"user"};
        searchSourceBuilder.fetchSource(includeFields, null);
        searchRequest.source(searchSourceBuilder);
        try {
            SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);

            for (SearchHit searchHit : searchResponse.getHits()) {
                String sourceAsString = searchHit.getSourceAsString();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }


        return "";
    }
}
